String Substitution Utilities

Substituting the first occurrence of a character string

This utility permits the JavaScript author to substitute one character string for another where it first appears in a given string.

// Substitute character string c2 for the first c1 in the string aString
function substFirst(aString, c1, c2)
{
	if (aString == "") return aString
	
	// find the character string
	var i = aString.indexOf(c1)
	
	// return original string if not found
	if (i < 0) return aString
	
	// extract the characters before and after the string
	var s1 = aString.substring(0, i)
	var s2 = aString.substring(i+c1.length, aString.length)
	
	// recombine with the new character string and return
	return s1+c2+s2
}

Substituting the last occurrence of a character string

This utility permits the JavaScript author to substitute one character string for another where it last appears in a given string.

// Substitute character string c2 for the last c1 in the string aString
function substLast(aString, c1, c2)
{
	if (aString == "") return aString
	
	// find the character string
	var i = aString.lastIndexOf(c1)
	
	// return original string if not found
	if (i < 0) return aString
	
	// extract the characters before and after the string
	var s1 = aString.substring(0, i)
	var s2 = aString.substring(i+c1.length, aString.length)
	
	// recombine with the new character string and return
	return s1+c2+s2
}

Substituting every occurrence of a character string

This utility permits the JavaScript author to substitute one character string for another every place it appears in a given string. Consider the examples below. The first two call the subst function and show the function's behavior. Then the viewsubst function shows the same behavior, but includes diagnostic writes to better demonstrate the process of the function.

// Substitute character string c2 for every c1 in aString
function subst(aString, c1, c2)
{
	if (aString == "") return aString
	if (c1 == "") return aString
	
	// avoid infinite recursion when substituting aa for a by
	// providing an offset into the string.
	var argc = subst.arguments.length
	if (argc < 4) {n = 0} else {n = subst.arguments[3]}

	// find the first occurrence of c1 after the threshold
	var i = aString.indexOf(c1, n)
	
	// stop recursion and return the current string when c1 not found
	if (i < 0) return aString
	
	// extract substrings s1 and s2 around the c1
	var s1 = aString.substring(0, i)
	var s2 = aString.substring(i+c1.length, aString.length)
	
	// recurse with this new string
	return subst(s1+c2+s2, c1, c2, (i+c2.length))
}
Copyright ©1998 by Charles River Media, All Rights Reserved